package com.tudouji.framework.task;


import _128._90._114._47.ormrpc.services.WSExportCustomerFacade.WSExportCustomerFacadeSrvProxy;
import _128._90._114._47.ormrpc.services.WSExportCustomerFacade.WSExportCustomerFacadeSrvProxyProxy;
import com.alibaba.fastjson.JSONObject;
import com.tudouji.common.enums.CopyTypeEnums;
import com.tudouji.common.enums.IsCopyEnums;
import com.tudouji.common.enums.KdCustomerKeyEnums;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.xml.XmlUtils;
import com.tudouji.project.copy.domain.Copyparam;
import com.tudouji.project.copy.service.ICopyparamService;
import com.tudouji.project.copy.service.impl.KdPostUtils;
import com.tudouji.project.customer.domain.Customer;
import com.tudouji.project.customer.domain.CustomerBalance;
import com.tudouji.project.customer.mapper.CustomerBalanceMapper;
import com.tudouji.project.customer.mapper.CustomerMapper;
import com.tudouji.project.customer.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客户同步Task
 */
@Slf4j
@Component("customerSynTask")
public class CustomerSynTask {

    @Autowired
    private ICopyparamService copyparamService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerBalanceMapper customerBalanceMapper;
    @Autowired
    private KdPostUtils kdPostUtils;

    private List<Customer> customerList = new ArrayList<>();

    public void customerSynTask() {
        //1、获取系统同步参数
        Copyparam copyparam = new Copyparam();
        copyparam.setType(CopyTypeEnums.CUSTOMER.getCode());
        copyparam.setIscopy(IsCopyEnums.YES.getCode());
        List<Copyparam> copyparams = this.copyparamService.selectCopyparamList(copyparam);
        //2、获取ERP客户
        customerList = this.customerService.selectCustomerList(new Customer());
        //3、获取金蝶客户
        kdPostUtils.login();
        WSExportCustomerFacadeSrvProxy customerProxy = new WSExportCustomerFacadeSrvProxyProxy();
        try {
            Object[] kdCustomers = customerProxy.exportCustomerData(0, Integer.MAX_VALUE);
            int rows = 10;
            int start = Integer.valueOf(copyparams.get(0).getBusinessPrefix());
            log.info("客户同步规则 " + copyparams.get(0).getParam());
            log.info("数据数量  " + kdCustomers.length);
            if (kdCustomers.length > 0) {
                if (kdCustomers.length == start) {
                    log.info("金蝶已同步到最后一条数据，修改同步业务前缀后，可重新同步！");
                    return;
                }
                int pageSize = (kdCustomers.length - start) / rows + 1;
                for (int i = 0; i < pageSize; i++) {
                    startSyn((start + i * rows), rows, copyparams.get(0));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return
     * @Author shaodong
     * @Description //分頁更新處理
     * @Date 11:51 2021/1/27
     * @Param
     **/
    private void startSyn(int start, int rows, Copyparam copyparam) throws java.rmi.RemoteException {
        WSExportCustomerFacadeSrvProxy customerProxy = new WSExportCustomerFacadeSrvProxyProxy();
        Object[] kdCustomers = customerProxy.exportCustomerData(start, rows);
        Date synTime = new Date();
        //3.1、处理金蝶返回后的数据，组装成json集合
        ArrayList<JSONObject> json_kdCustomers = new ArrayList<>();
        for (int i = 0; i < kdCustomers.length; i++) {
            JSONObject kdCustomer = XmlUtils.getXmlAttribute(kdCustomers[i].toString()
                    , new String[]{KdCustomerKeyEnums.NAME.getCode(), KdCustomerKeyEnums.NUMBER.getCode(), "isInternalCompany"});
            json_kdCustomers.add(kdCustomer);
        }
        //b)客户同步规则=1，则ERP系统新增该客户，完成处理
        String param = copyparam.getParam();
        if (StringUtils.equals(param, "1")) {
            Customer insertCustomer = new Customer();
            for (int j = 0; j < json_kdCustomers.size(); j++) {
                JSONObject kdSupp = json_kdCustomers.get(j);
                if (kdSupp != null) {
                    insertCustomer.setKingdeenum(kdSupp.getString(KdCustomerKeyEnums.NUMBER.getCode()));
                    List<Customer> insertCustomers = customerService.selectCustomerList(insertCustomer);
                    if (insertCustomers.size() == 0) {
                        //loading...
                        insertCustomer(insertCustomer, kdSupp, synTime);
                    }
                }
            }
        }
        //c)客户同步规则=2：
        //i.ERP系统是否有同名、且编号空的客户存在则认为该客户和金蝶系统客户为同一客户，同步金蝶系统客户编号
        //ii.ERP系统有同名但编号不同的客户，同步状态（同步失败）、提示信息（客户信息同名）写入ERP系统客户表中
        else if (StringUtils.equals(param, "2")) {
            for (int j = 0; j < customerList.size(); j++) {
                Customer updateSupp = customerList.get(j);
                if (null != updateSupp) {
                    for (int k = 0; k < json_kdCustomers.size(); k++) {
                        JSONObject kdSupp = json_kdCustomers.get(k);
                        String name = kdSupp.getString(KdCustomerKeyEnums.NAME.getCode());
                        if (StringUtils.equalsAny(StringUtils.trimLR(name), StringUtils.trimLR(updateSupp.getName()))) {
                            if (StringUtils.isBlank(updateSupp.getKingdeenum())) {
                                updateSupp.setKingdeenum(kdSupp.getString(KdCustomerKeyEnums.NUMBER.getCode()));
                                updateCustomer(synTime, "同步成功", 2, updateSupp);
                            } else {
                                String number = kdSupp.getString(KdCustomerKeyEnums.NUMBER.getCode());
                                if (!StringUtils.equals(number, updateSupp.getKingdeenum())) {
                                    updateCustomer(synTime, "客户信息同名", 3, updateSupp);
                                }
                            }
                        }

                    }
                }
            }

        }
        //d)ERP系统没有同名客户，则新增该客户信息到ERP系统
        /*for (int j = 0; j < json_kdCustomers.size(); j++) {
            JSONObject kdSupp = json_kdCustomers.get(j);
            if (kdSupp != null) {
                Customer insertCustomer = new Customer();
                insertCustomer.setName(StringUtils.trimLR(kdSupp.getString(KdCustomerKeyEnums.NAME.getCode())));
                List<Customer> insertCustomers = customerService.selectCustomerList(insertCustomer);
                if (insertCustomers.size() == 0) {
                    insertCustomer(insertCustomer, kdSupp, synTime);
                }
            }
        }*/

        copyparam.setBusinessPrefix(String.valueOf(start + kdCustomers.length));
        copyparam.setLastupdatetime(synTime);
        copyparamService.updateCopyparam(copyparam);
    }

    private void updateCustomer(Date synTime, String sychinfo, Integer status, Customer updateSupp) {
        updateSupp.setSynchinfo(sychinfo);
        updateSupp.setSynchstat(status);
        updateSupp.setSynchtime(synTime);
        customerMapper.updateCustomer(updateSupp);
    }

    /**
     * @return
     * @Author shaodong
     * @Description //插入客户
     * @Date 18:20 2021/1/26
     * @Param
     **/
    private void insertCustomer(Customer insertCustomer, JSONObject kdSupp, Date synTime) {
        insertCustomer.setName(StringUtils.trimLR(kdSupp.getString(KdCustomerKeyEnums.NAME.getCode())));
        insertCustomer.setKingdeenum(kdSupp.getString(KdCustomerKeyEnums.NUMBER.getCode()));
        insertCustomer.setSynchtime(synTime);
        insertCustomer.setSynchstat(2);//同步状态:1-未同步,2-同步成功,3-同步失败
        insertCustomer.setStatus(1);
        insertCustomer.setGuid(IdUtils.fastSimpleUUID());
        insertCustomer.setSynchinfo("同步成功");
        insertCustomer.setCreatetime(synTime);
        insertCustomer.setType(1);
        customerMapper.insertCustomer(insertCustomer);
    }

    /**
     * 新增系统批量，每天晚上11点55跑，将客户表中的相应数据跑到每日余额表中，
     * business_date记录为当天的日期，系统每次清掉当天数据之后、再写入当天数据。
     */
    public void customerBalanceTask(){
        Date nowDay = DateUtils.getNowDay();
        customerBalanceMapper.deleteCustomerBalanceByDay(nowDay);

        Customer customer = new Customer();
        customer.setStatus(1);
        List<Customer> customers = customerMapper.selectCustomers(customer);

        for (int i = 0; i < customers.size(); i++) {
            Customer c = customers.get(i);
            if (StringUtils.isEmpty(c.getKingdeenum())){
                continue;
            }

            CustomerBalance customerBalance = new CustomerBalance();
            customerBalance.setCustomerGuid(c.getGuid());
            customerBalance.setKingdeenum(c.getKingdeenum());
            customerBalance.setBusinessDate(nowDay);
            customerBalance.setName(c.getName());
            customerBalance.setPrebalance(c.getPrebalance());
            customerBalance.setRecbalance(c.getRecbalance());
            customerBalance.setRecbalanceManul(c.getRecbalanceManual());
            customerBalance.setCreateTime(DateUtils.getNowDate());
            customerBalanceMapper.insertCustomerBalance(customerBalance);
        }

    }

}
